<template>
  <el-dialog
    v-model="dialogVisible"
    :title="todo ? '编辑待办' : '新建待办'"
    width="600px"
    destroy-on-close
    @close="handleCancel"
  >
    <el-form :model="todoForm" :rules="todoRules" ref="todoFormRef" label-width="100px">
      <el-form-item label="标题" prop="title">
        <div class="input-with-voice">
          <el-input v-model="todoForm.title" placeholder="请输入待办事项标题" />
          <div
            class="voice-icon"
            @click="handleTitleVoiceClick"
            :class="{ 'recording': titleRecording, 'disabled': !titleVoiceSupported }"
            :title="titleVoiceSupported ? (titleRecording ? '正在录音中...' : '点击开始语音输入标题') : '浏览器不支持语音识别'"
          >
            <el-icon :size="18">
              <Microphone />
            </el-icon>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <div class="input-with-voice">
          <el-input
            v-model="todoForm.description"
            type="textarea"
            :rows="3"
            placeholder="添加描述（选填）"
          />
          <div
            class="voice-icon"
            @click="handleDescriptionVoiceClick"
            :class="{ 'recording': descriptionRecording, 'disabled': !descriptionVoiceSupported }"
            :title="descriptionVoiceSupported ? (descriptionRecording ? '正在录音中...' : '点击开始语音输入描述') : '浏览器不支持语音识别'"
          >
            <el-icon :size="18">
              <Microphone />
            </el-icon>
          </div>
        </div>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="todoForm.categoryId" placeholder="选择分类" style="width: 100%">
              <el-option label="无分类" :value="null" />
              <el-option
                v-for="cat in categories"
                :key="cat.id"
                :label="cat.name"
                :value="cat.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="todoForm.priority" placeholder="选择优先级" style="width: 100%">
              <el-option label="低" value="low" />
              <el-option label="普通" value="normal" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="截止时间" prop="dueDate">
        <el-date-picker
          v-model="todoForm.dueDate"
          type="datetime"
          placeholder="选择截止时间（选填）"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="提醒" prop="reminder">
        <el-select v-model="todoForm.reminder" placeholder="选择提醒时间" style="width: 100%">
          <el-option label="不提醒" value="none" />
          <el-option label="截止时" value="0" />
          <el-option label="提前15分钟" value="15" />
          <el-option label="提前30分钟" value="30" />
          <el-option label="提前1小时" value="60" />
          <el-option label="提前1天" value="1440" />
        </el-select>
      </el-form-item>
      <el-form-item label="标记为重要">
        <el-switch v-model="todoForm.important" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
  
  <!-- 标题语音输入组件 -->
  <VoiceTodoInput
    mode="float"
    :show-overlay="true"
    label="正在语音输入标题..."
    tip-text="说出待办标题，点击停止按钮完成输入"
    placeholder="请说出待办标题"
    @parse-complete="handleTitleVoiceComplete"
    @recording-start="handleTitleRecordingStart"
    @recording-stop="handleTitleRecordingStop"
    ref="titleVoiceInputRef"
  />
  
  <!-- 描述语音输入组件 -->
  <VoiceTodoInput
    mode="float"
    :show-overlay="true"
    label="正在语音输入描述..."
    tip-text="说出待办描述，点击停止按钮完成输入"
    placeholder="请说出待办描述"
    @parse-complete="handleDescriptionVoiceComplete"
    @recording-start="handleDescriptionRecordingStart"
    @recording-stop="handleDescriptionRecordingStop"
    ref="descriptionVoiceInputRef"
  />
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Microphone } from '@element-plus/icons-vue'
import VoiceTodoInput from '@/components/common/VoiceTodoInput.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  todo: {
    type: Object,
    default: null
  },
  categories: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'save', 'cancel'])

const dialogVisible = ref(false)
const todoFormRef = ref(null)
const titleVoiceInputRef = ref(null)
const descriptionVoiceInputRef = ref(null)

// 录音状态
const titleRecording = ref(false)
const descriptionRecording = ref(false)

// 是否支持语音识别
const titleVoiceSupported = ref(false)
const descriptionVoiceSupported = ref(false)

// 监听语音输入组件是否支持语音
watch(() => titleVoiceInputRef.value?.isVoiceSupported, (val) => {
  if (val !== undefined) {
    titleVoiceSupported.value = val
  }
}, { immediate: true })

watch(() => descriptionVoiceInputRef.value?.isVoiceSupported, (val) => {
  if (val !== undefined) {
    descriptionVoiceSupported.value = val
  }
}, { immediate: true })

// 处理标题语音图标点击
const handleTitleVoiceClick = () => {
  if (!titleVoiceInputRef.value) return
  
  if (!titleVoiceSupported.value) {
    return
  }
  
  // 如果正在录音，停止录音；否则开始录音
  if (titleRecording.value) {
    titleVoiceInputRef.value.stopRecording()
  } else {
    // 如果描述正在录音，先停止
    if (descriptionVoiceInputRef.value && descriptionVoiceInputRef.value.isRecording) {
      descriptionVoiceInputRef.value.stopRecording()
    }
    titleVoiceInputRef.value.startRecording()
  }
}

// 处理描述语音图标点击
const handleDescriptionVoiceClick = () => {
  if (!descriptionVoiceInputRef.value) return
  
  if (!descriptionVoiceSupported.value) {
    return
  }
  
  // 如果正在录音，停止录音；否则开始录音
  if (descriptionRecording.value) {
    descriptionVoiceInputRef.value.stopRecording()
  } else {
    // 如果标题正在录音，先停止
    if (titleVoiceInputRef.value && titleVoiceInputRef.value.isRecording) {
      titleVoiceInputRef.value.stopRecording()
    }
    descriptionVoiceInputRef.value.startRecording()
  }
}

// 处理标题语音输入完成
const handleTitleVoiceComplete = (parsedTodo, originalText) => {
  todoForm.title = originalText.trim() || todoForm.title
}

// 处理标题录音开始
const handleTitleRecordingStart = () => {
  titleRecording.value = true
  // 如果描述正在录音，先停止
  if (descriptionVoiceInputRef.value && descriptionVoiceInputRef.value.isRecording) {
    descriptionVoiceInputRef.value.stopRecording()
  }
}

// 处理标题录音停止
const handleTitleRecordingStop = () => {
  titleRecording.value = false
}

// 处理描述语音输入完成
const handleDescriptionVoiceComplete = (parsedTodo, originalText) => {
  todoForm.description = originalText.trim() || todoForm.description
}

// 处理描述录音开始
const handleDescriptionRecordingStart = () => {
  descriptionRecording.value = true
  // 如果标题正在录音，先停止
  if (titleVoiceInputRef.value && titleVoiceInputRef.value.isRecording) {
    titleVoiceInputRef.value.stopRecording()
  }
}

// 处理描述录音停止
const handleDescriptionRecordingStop = () => {
  descriptionRecording.value = false
}

// 表单数据
const todoForm = reactive({
  title: '',
  description: '',
  categoryId: null,
  priority: 'normal',
  dueDate: null,
  reminder: 'none',
  important: false
})

// 表单验证规则
const todoRules = {
  title: [{ required: true, message: '请输入待办事项标题', trigger: 'blur' }]
}

// 监听 modelValue 变化
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    // 初始化表单数据
    if (props.todo) {
      Object.assign(todoForm, {
        title: props.todo.title,
        description: props.todo.description,
        categoryId: props.todo.categoryId,
        priority: props.todo.priority,
        dueDate: props.todo.dueDate ? new Date(props.todo.dueDate) : null,
        reminder: props.todo.reminder,
        important: props.todo.important
      })
    } else {
      // 新建模式，重置表单
      Object.assign(todoForm, {
        title: '',
        description: '',
        categoryId: null,
        priority: 'normal',
        dueDate: null,
        reminder: 'none',
        important: false
      })
    }
  }
})

// 监听 dialogVisible 变化，同步到 modelValue
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 处理保存
const handleSave = () => {
  todoFormRef.value.validate((valid) => {
    if (valid) {
      const formData = {
        ...todoForm,
        dueDate: todoForm.dueDate ? todoForm.dueDate.toLocaleString() : null
      }
      emit('save', formData)
      dialogVisible.value = false
    }
  })
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  emit('cancel')
}
</script>

<style scoped>
.input-with-voice {
  position: relative;
  width: 100%;
}

.input-with-voice :deep(.el-input),
.input-with-voice :deep(.el-textarea) {
  width: 100%;
}

.input-with-voice :deep(.el-textarea__inner) {
  padding-right: 40px;
}

.voice-icon {
  position: absolute;
  right: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 50%;
  color: #909399;
  z-index: 10;
}

/* 普通输入框: 图标居中 */
.input-with-voice :deep(.el-input) ~ .voice-icon {
  top: 50%;
  transform: translateY(-50%);
}

/* textarea: 图标在右上角 */
.input-with-voice :deep(.el-textarea) ~ .voice-icon {
  top: 8px;
}

.voice-icon:hover:not(.disabled) {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.voice-icon.recording {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
}

.voice-icon.recording .el-icon {
  animation: pulse 1.5s ease-in-out infinite;
}

.voice-icon.disabled {
  cursor: not-allowed;
  opacity: 0.4;
}

.voice-icon .el-icon {
  transition: all 0.3s;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}
</style>

